package com.github.thinwonton.activemq.showcase.sample.helloworld.topic;

import com.github.thinwonton.activemq.showcase.sample.utils.ActiveMQManager;

import javax.jms.*;

public class Producer {
    public static final String TOPIC_NAME = "test-topic";

    public static void main(String[] args) {
        System.out.println("Producer started!");

        String message_body = "消息 : " + System.currentTimeMillis();

        try {
            //获取连接
            Connection connection = ActiveMQManager.createConnection();

            //启动连接
            connection.start();

            //开启会话，第一个参数指定是否使用事务，第二个参数指示消费者是否需要手动应答自己已经接收到消息
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

            //建立话题
            Topic topic = session.createTopic(TOPIC_NAME);

            //获取消息生产者对象
            MessageProducer producer = session.createProducer(topic);

            //建立消息对象
            TextMessage message = session.createTextMessage(message_body);

            //发送消息
            producer.send(message);

            System.out.println("成功发送消息：" + message.getText());

            producer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Producer end!");
    }
}
